﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using TanWeb.Helpers;
using TanWeb.Models.Entities;
using TanWeb.Models.DataAccess.Infrastructure;
using TanWeb.Models.Entities.Master;
using System.Collections;

namespace TanWeb.Models.DataAccess
{
    public class ImageDataAccess : BaseDataAccess
    {
        //===============================================================
        //  コンストラクタ等宣言
        //===============================================================
        #region /***    Constructor Destructor Declared    ***/

        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="dbContext">データベースコンテキスト</param>
        public ImageDataAccess(DbContext dbContext) : base(dbContext) { }

        #endregion

        public int RegisterImage(string groupId, string subGroupId, int productId, int imageIndex, string date, bool isFirstRecord = true)
        {
            // ログを記述する
            logger.Info("\t\tStart DataAccess: Image; RegisterImage");
            string sql = string.Empty;
            int result = 0;
            int id = 1;

            try
            {
                ArrayList fileNameList = (ArrayList)Utils.GetSession(Constants.SESSION_UPLOADED_FILENAME);

                string imageName = string.Empty;

                foreach (UploadedFile file in fileNameList)
                {
                    if (file.index.Contains(imageIndex.ToString() + ";"))
                    {
                        imageName = file.fileName;

                        string findId = id.ToString();

                        if (!isFirstRecord)
                        {
                            findId = string.Format(@"
                            (SELECT ISNULL(MAX(id) + 1, 1)
                            FROM Image
                            WHERE GroupId = {0}
                                AND SubGroupId = {1}
                                AND ProductId = {2})",
                                groupId, subGroupId, productId);
                        }

                        sql = string.Format(@"
                            DECLARE @id int
                            SET @id = {5}
                            INSERT INTO Image (id, GroupId, SubGroupId, ProductId, ImageName, del_flg, UpdateDate) 
                            VALUES (@id, {0}, {1}, {2}, '{3}', 0, '{4}')"
                                , groupId, subGroupId, productId, imageName, date, findId);

                        result = this.DbContext.Database.ExecuteSqlCommand(sql);

                        id++;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("\t\tError DataAccess: Image; Function: RegisterImage", ex);
                throw ex;
            }

            logger.Info("\t\tEnd DataAccess: Image; Function: RegisterImage");
            return result;
        }

        public List<string> GetImageName(string groupId, string subGroupId, string productId, int imageIndex)
        {
            // ログを記述する
            logger.Info("\t\tStart DataAccess: Image; GetImageName");
            string sql = @"SELECT ImageName
                           FROM Image
                           WHERE GroupId = {0}
                               AND SubGroupId = {1}
                               AND ProductId = {2}";

            List<string> listImageName = new List<string>();

            try
            {
                if (imageIndex > 0)
                {
                    sql += @" AND id = {3}";
                }

                sql += " ORDER BY id DESC";

                sql = string.Format(sql, groupId, subGroupId, productId, imageIndex);

                listImageName = this.DbContext.Database.SqlQuery<string>(sql).ToList();
            }
            catch (Exception ex)
            {
                logger.Error("\t\tError DataAccess: Image; Function: GetImageName", ex);
                throw ex;
            }

            logger.Info("\t\tEnd DataAccess: Image; Function: GetImageName");
            return listImageName;
        }

        public List<Image> GetListImage(string groupId, string subGroupId, string productId)
        {
            // ログを記述する
            logger.Info("\t\tStart DataAccess: Image; GetListImageName");
            string sql = @"
                            SELECT *
                            FROM Image";
            List<Image> listImageName = new List<Image>();

            try
            {
                if (groupId != null && subGroupId != null && productId != null) 
                {
                    sql = string.Format(sql + @" 
                                WHERE GroupId = {0}
                                    AND SubGroupId = {1}
                                    AND ProductId = {2}
                                    AND del_flg = 0
                                ORDER BY id ASC"
                            , groupId, subGroupId, productId);
                }

                listImageName = this.DbContext.Database.SqlQuery<Image>(sql).ToList();
            }
            catch (Exception ex)
            {
                logger.Error("\t\tError DataAccess: Image; Function: GetListImageName", ex);
                throw ex;
            }

            logger.Info("\t\tEnd DataAccess: Image; Function: GetListImageName");
            return listImageName;
        }

        public int DeleteImage(string groupId, string subGroupId, string productId, string updateTime)
        {
            // ログを記述する
            logger.Info("\t\tStart DataAccess: Image; DeleteImage");
            int result = 0;

            try
            {
                string sql = string.Format(@" 
                            Update Image
                            SET del_flg = 1,
                                UpdateDate = '{3}'
                            WHERE GroupId = {0}
                                AND SubGroupId = {1}
                                AND ProductId = {2}"
                        , groupId, subGroupId, productId, updateTime);

                result = this.DbContext.Database.ExecuteSqlCommand(sql);
            }
            catch (Exception ex)
            {
                logger.Error("\t\tError DataAccess: Image; Function: DeleteImage", ex);
                throw ex;
            }

            logger.Info("\t\tEnd DataAccess: Image; Function: DeleteImage");
            return result;
        }
    }
}